#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   gfs2_mkfs.sh
# Version:    1.0
# Date:       2013/11/14
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    02系统基本功能-05本地服务-02分布式节点服务-01生成gfs2文件系统
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/11/14
#             - mkfs.gfs2 dev/sdaN.
# ----------------------------------------------------------------------

##! @TODO: check /dev/sda
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_setup()
{
    trap do_cleanup INT EXIT
    # check commands
    exists pvcreate vgcreate lvcreate fdisk
    EchoResult "exists commands"

    # check free disk
    echo "before test, pls make sure the last disk is free for mkfs, large than 10GB\
          or the last disk will be destroyed"

    # get last disk
    DISK_FILE=`mktemp` 
    ls /dev/sd* | sort -r > ${DISK_FILE}

    disk=""
    LAST_DISK=""
    i=1
    while true; do
        disk=`sed -n ${i}p ${DISK_FILE}`

        if [ ${#disk} -lt 9 ]; then
            i=$((i+1))
        else
            LAST_DISK="$disk"
            break
        fi
    
    done

    echo "free disk: ${LAST_DISK}"

    VG=gfsvg
    vgdisplay ${VG} 
    if [ $? -eq 0 ];then
            umount -f /tmp/gfs2
            echo -e "y\ny\n" | vgremove gfsvg
    fi
    # pvcreate
    echo y | pvcreate ${LAST_DISK}
    EchoResult "pvcreate"

    # vgcreate
    vgcreate ${VG} ${LAST_DISK}
    EchoResult "vgcreate"

    # lvcreate
    LV=gfslv
    DISK_SIZE=`fdisk -l | grep ${LAST_DISK} | awk '{print $4}'`
    if [ ${#DISK_SIZE} -gt 7 ];then
        size=8G
    else
        echo "${LAST_DISK} is less than ${size}, pls check"
        exit 1
    fi

    lvcreate -L ${size} -n ${LV} ${VG}
    EchoResult "lvcreate"
    

    trap do_cleanup EXIT

}

##! @TODO: mkfs.gfs2
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_test()
{
   DM=/dev/${VG}/${LV}
   echo y | mkfs.gfs2 -p lock_nolock -j 8 ${DM}
   EchoResult "mkfs.gfs2"
}

##! @TODO: cleanup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_cleanup()
{
    rm -rf "${DISK_FILE}"
    lvremove -f ${DM}
    vgremove -f ${VG}
}


# include lib files
if [ -z "$SFROOT" ]
then
    echo "SFROOT is null, pls check"
    exit 1
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi


. ${SFROOT}/lib/Echo.sh
. ${CMDLIB}/lib/Net.sh


do_setup
do_test
EchoResult "testcase: mkfs.gfs2"
